import Axios, { AxiosError,type AxiosRequestConfig,type AxiosResponse } from "axios";
import { ElNotification } from "element-plus";
import config from "@/config";
import type { Response } from "./model";
const {BASE_URL,SUCCESS_CODE} = config;
Axios.defaults.baseURL=BASE_URL;
// 拦截头
{
    Axios.interceptors.request.use((config:AxiosRequestConfig) =>{
        const token=sessionStorage.getItem("token");
        if(!token) return config;
        if(!config.headers) return config;
        typeof config.headers.set === "function" && config.headers.set("token",token)
        return config;
    },error=>{
        throw error;
    })
}


{
    Axios.interceptors.response.use((response:AxiosResponse<Response<any>>) => {
    if (response.config.responseType === 'blob') {
      return response;
    } else{
      switch (response.data?.code) {
        case SUCCESS_CODE:
          return response.data?.data;
        default:
          let useDefaultErrorHandler = true;
          const hiddenDefaultErrorHandler = () => useDefaultErrorHandler = false;
          setTimeout(()=>{
            if(useDefaultErrorHandler){
              ElNotification.closeAll()
              ElNotification({
                title:"提示",
                message:"服务器开小差了,请稍后",
                type:"error",
                duration:2000
              })
            }
          },0)
          throw {...response,hiddenDefaultErrorHandler}
      }
    }
  },
  (error: AxiosError) => {
    let useDefaultErrorHandler = true;
    const hiddenDefaultErrorHandler = () => useDefaultErrorHandler = false;
     setTimeout(()=>{
      if(useDefaultErrorHandler){
        ElNotification.closeAll()
        ElNotification({
          title:"提示",
          message:"服务器开小差了,请稍后",
          type:"error",
          duration:2000
        })
      }
    },0)
    throw {...error,hiddenDefaultErrorHandler}
  }
)
}




export default Axios;